/**
 * Created by chenxq on 2017/12/11.
 */
import React, {PureComponent} from "react";
import {connect} from "dva";
import {Button, Card, Divider, Form, message, Modal, Popconfirm, Radio, Select, Table, Upload} from "antd";
import {Link, Redirect, Route, Switch} from "dva/router";
import PageHeaderLayout from "../../layouts/PageHeaderLayout";
import {SearchInput} from "../../components/Customer/headerForm";
import styles from "./customer.less";
import {convertLongToDate, findObjByKey} from "../../utils/index";
import {customerStatus, listParams} from "../defaultData";
import AddCustomer from "../../components/Customer/AddCustomer";
import Allocate from "../../components/Customer/Allocate";
import Apply from "../../components/Customer/Apply";
import request, {getToken} from "../../utils/request";
import PREFIX from "../../utils/prefix-hot";
const FormItem = Form.Item;
const {Option} = Select;
const PublicImportUrl = `${PREFIX}/v1/customer/excel/public/import`;  //公共导入
const PrivateImportUrl = `${PREFIX}/v1/customer/excel/private/import`; // 私有导入
const DownloadUrl = `${PREFIX}/v1/customer/excel/download`;

@connect(state => ({
  customer: state.customer,
  user: state.usermanagement
}))
@Form.create()
export default class extends PureComponent {
  static defaultProps = {
    params: {}  // 公共
  }
  state = {
    pagination: {
      ...listParams,
      ...this.props.params

    },
    addKey: Math.random(),
    addVisible: false,
    allocateVisible: false,
    acclocateKey: Math.random(),
    applyVisible: false,
    applyKey: Math.random(),
    loseStep: this.props.params.loseStep || 1,
    changeVisible: false,
    changeStateValue: 0 // 初始池
  };
  defaultData = {
    name: '',
    template: '',
    remark: '',
    content: '',
  };
  selectedRowKeys = [];
  columns = [{
    title: '客户姓名',
    dataIndex: 'name',
  },
    //   {
    //   title: '客户类型',
    //   dataIndex: 'type',
    //   render(type){
    //     let obj = findObjByKey(CustomerTypeArr,type,"key");
    //     return obj ? obj.name : "未知"
    //   }
    // },
    //   {
    //   title: '渠道',
    //   dataIndex: 'channel',
    //   render:(channel)=>{
    //     let obj = findObjByKey(channelList,channel,"key");
    //     return obj ? obj.name : "未知"
    //   }
    // },
    {
      title: '等级',
      dataIndex: 'grade'
    }, {
      title: '跟进人',
      dataIndex: 'followerName'
    }, {
      title: '跟进天数',
      dataIndex: 'followDays'
    }, {
      title: "最后跟进时间",
      dataIndex: "lastFollowTime",
      render: (datetime) => {
        return datetime ? convertLongToDate(datetime) : ""
      }
    }, {
      title: "认领时间",
      dataIndex: "ownTime",
      render: (datetime) => {
        return datetime ? convertLongToDate(datetime) : ""
      }
    },
    //   {
    //   title:"创建时间",
    //   dataIndex:"createTime",
    //   render:(datetime)=>{
    //     return datetime ? convertLongToString(datetime) : "";
    //   }
    // },
    {
      title: "客户状态",
      dataIndex: "state",
      render: (state) => {
        let obj = findObjByKey(customerStatus, state);
        return obj ? obj.name : "未知"
      }
    }, {
      title: "操作",
      dataIndex: "id",
      render: (id, record) => {
        let params = this.props.params;
        switch (params.state) {
          case 'INVALID':  // 无效
          case 'INIT':
            return (<div className={styles.operations}>
              {this.gethandleNode('detail', record)}
              <Divider type="vertical"/>
              {this.gethandleNode('delete', record)}
            </div>);
            break;
          case 'FOLLOW':
            return (<div className={styles.operations}>
              {this.gethandleNode('detail', record)}
              <Divider type="vertical"/>
              {this.gethandleNode('intention', record)}
            </div>);
            break; // 营销
          case 'LOSE':
            return (<div className={styles.operations}>
              {this.gethandleNode('detail', record)}
              <Divider type="vertical"/>
              {this.gethandleNode('changeState', record)}
            </div>);
            break; //输单
          case 'INTENTION': //意向
          case 'MAINTAIN': // 签约
          case 'SUCCESS':
            return (<div className={styles.operations}>
              {this.gethandleNode('detail', record)}
            </div>);
            break; //赢单
          default:
            return '';
        }
      }
    }];
  gethandleNode = (handleType, record) => {
    switch (handleType) {
      case 'detail' :
        return (<Link to={`/customer/detail/${record.id}`}>详情</Link>);
        break;
      case 'delete':
        return (<Popconfirm title="确认要删除该客户?" onConfirm={this.remove.bind(this, [record.id])}><a>删除</a></Popconfirm>);
        break;
      case 'changeState':
        return (<a onClick={this.changeState.bind(this, record)}>划转</a>);
        break;
      case 'intention' :
        return (<a onClick={this.handleIntention.bind(this, record.id)}>意向</a>);
        break;
    }
    return null;
  }

  //意向
  handleIntention = (customerId) => {
    let _this = this;
    request(`/v1/customer/intend/${customerId}`, {
      method: 'POST',
      body: {}
    }).then(jsonData => {
      if (jsonData.result) {
        message.success('操作成功', 0.8, () => {
          _this.getList();
        });
      } else {
        message.error(jsonData.msg || '操作失败')
      }
    })
  }

  remove = (ids) => {
    let _this = this;
    this.props.dispatch({
      type: 'customer/fetchRemove',
      payload: ids
    }).then(jsonData => {
      if (jsonData.result) {
        message.success('删除成功', 0.8, () => {
          _this.getList();
        })
      } else {
        message.error(jsonData.msg);
      }
    })
  }

  handleSearch = (search) => {
    let {pagination} = this.state;
    pagination = Object.assign(pagination, search);
    this.setState({
      pagination
    }, () => {
      this.getList();
    })
  }

  getList = (page = {current: 1}) => {
    let pagination = {
      ...this.state.pagination,
      ...page
    };
    this.setState({
      pagination
    })
    let {params} = this.props;
    this.props.dispatch({
      type: 'customer/fetchList',
      payload: Object.assign({}, params, pagination)
    })
  }
  // 添加客户
  addCustomer = (params) => {
    let _this = this;
    params.type = this.props.params.type == 'PUBLIC' ? 'PUBLIC' : 'PRIVATE';
    this.props.dispatch({
      type: 'customer/fetchAdd',
      payload: params
    }).then(jsonData => {
      if (jsonData.result) {
        message.success('添加成功', 0.8, () => {
          // 关闭窗口
          _this.getList();
          _this.setState({
            addVisible: false
          })
        })
      } else {
        message.error(jsonData.msg)
      }
    })
  }
  //
  handleAdd = () => {
    this.setState({
      addKey: Math.random(),
      addVisible: true
    })
  }
  handleAllocate = () => {
    if (this.props.user.groupList.length == 0) {
      message.error('请先添加坐席用户');
      return;
    }
    this.setState({
      acclocateKey: Math.random(),
      allocateVisible: true
    })
  }
  //分配客户
  allocate = (params) => {
    console.log('allocate', params);
    params.type = this.props.params.type;  // 分配的客户类型
    this.props.dispatch({
      type: 'customer/allocate',
      payload: params
    }).then(jsonData => {
      if (jsonData.result) {
        message.success('分配成功', 0.8, () => {
          this.setState({
            allocateVisible: false
          })
          this.getList();
        })
      } else {
        message.error('分配失败');
      }
    })

  }
  // 获取分组用户
  getUserByGroup = () => {
    this.props.dispatch({
      type: 'usermanagement/fetchListByGroup',
      payload: {}
    })
  }

  getHeader() {
    let {params} = this.props;
    let str;
    switch (params.state) {
      case 'INIT':
        str = params.type === 'PUBLIC' ? '公共资源池' : '私有资源池';
        break;
      case 'FOLLOW' :
        str = '营销客户';
        break;
      case 'INTENTION' :
        str = '意向客户';
        break;
      case 'MAINTAIN' :
        str = '签约客户';
        break;
      case 'LOSE' :
        str = '输单客户';
        break;
      case 'SUCCESS' :
        str = "赢单客户";
        break;
      case 'INVALID' :
        str = '无效客户';
        break;
      default :
        str = '其他';
    }
    return str;
  }

  // 下载模板
  download = () => {
    window.open(DownloadUrl);
  };

  checkFileList = (file, fileList) => {
    const MAX_FILE_SIZE = 5 * 1024 * 1024;//100kb
    if (file && file.size && file.size > MAX_FILE_SIZE) {
      message.warn(`文件大小不能大于${MAX_FILE_SIZE / 1024 / 1024}MB`);
      return false;
    }
  };
  //上传模板
  upload = (info, _this) => {
    let status = info.file.status;
    if (status === 'done') {
      let {response} = info.file;
      if (response.result) {
        message.success(`${info.file.name} 文件上传成功`);
        _this.getList();
      } else {
        message.warn(`${response.msg}`);
      }

    } else if (status === 'error') {
      message.error(`${info.file.name} 文件上传失败`);
    }

  }
  //申请客户
  handleApply = () => {
    this.setState({
      applyVisible: true,
      applyKey: Math.random()
    })
  }

  apply = (params) => {
    let _this = this;
    this.props.dispatch({
      type: 'customer/fetchApply',
      payload: params
    }).then(jsonData => {
      if (jsonData.result) {
        message.success('申请成功', 0.8, () => {
          _this.getList();
          _this.setState({
            applyVisible: false
          })
        })
      } else {
        message.error(jsonData.msg)
      }
    })
  }
  //做单步骤
  onChangeLoseStep = (e) => {
    let value = e.target.value;
    let {loseStep, pagination} = this.state
    if (value != loseStep) {
      this.setState({
        loseStep: value,
        pagination: {
          ...pagination,
          loseStep: value
        }
      }, () => {
        this.getList();
      });
    }
  }

  changeState = () => {
    this.setState({
      changeVisible: true,
      changeStateValue: 0
    })
  }
  // 划转提交
  changeStateSub = () => {
    let {changeStateValue} = this.state;
    let _this = this;
    if (this.selectedRowKeys.length <= 0) {
      message.error('请选择要划转的客户');
      return;
    }
    let params = {
      customerIds: [...this.selectedRowKeys],
    }
    if (changeStateValue) {
      params.type = changeStateValue;
    }
    this.props.dispatch({
      type: 'customer/fetchShift',
      payload: params
    }).then(jsonData => {
      if (jsonData.result) {
        message.success('划转成功', 0.8, () => {
          _this.getList();
        })
      } else {
        message.error(jsonData.msg || '划转失败');
      }
    })
  }


  componentDidMount() {
    this.getList();
    if ("INIT" === this.props.params.state) {
      this.getUserByGroup();
    }
  }


  render() {
    let {getFieldDecorator} = this.props.form;
    let {editObj} = this.state;
    let {params} = this.props;
    let tableRow = {};
    let _this = this;
    if (['INIT', 'LOSE', 'INVALID','FOLLOW'].indexOf(params.state) >= 0) {
      tableRow.rowSelection = {
        onChange(selectedRowKeys, selectedRows){
          _this.selectedRowKeys = selectedRowKeys;
        }
      }
    }
    return (<PageHeaderLayout title={this.getHeader()}>
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>
            <div className="flex-row">
              <div className={"flex1 " + styles.searchBtn}>
                {'INIT' === params.state && <Button type="primary" onClick={this.handleAllocate}>分配客户</Button>}
                {/*{'FOLLOW'===params.state && <Button type="primary" onClick={this.handleApply}>申请客户</Button>}*/}
                {'FOLLOW' === params.state &&
                <Button type="primary" style={{marginLeft: '20px'}} onClick={this.changeState}>划转</Button>}
                {['INIT', 'FOLLOW'].indexOf(params.state) >= 0 &&
                <Button icon="plus" onClick={this.handleAdd}>新建客户</Button>}
                {['INIT', 'FOLLOW'].indexOf(params.state) >= 0 &&
                <Upload action={params.type === "PUBLIC" ? PublicImportUrl : PrivateImportUrl}
                        headers={{"auth-token": getToken()}}
                        showUploadList={false}
                        onChange={(info) => {
                          this.upload(info, this)
                        }}
                        beforeUpload={(file, fileList) => {
                          return this.checkFileList(file, fileList);
                        }}
                >
                  <Button style={{marginRight: '8px'}} icon="to-top">批量导入</Button>
                </Upload>}
                {'INIT' === params.state && <Button icon="download" onClick={this.download}>下载模板</Button>}
                {'LOSE' === params.state &&
                <Radio.Group value={this.state.loseStep} onChange={this.onChangeLoseStep} style={{marginBottom: 16}}>
                  <Radio.Button value={1}>营销失败</Radio.Button>
                  <Radio.Button value={2}>无意愿</Radio.Button>
                  <Radio.Button value={3}>做单成功</Radio.Button>
                  <Radio.Button value={0}>其他</Radio.Button>
                </Radio.Group>}
                {'LOSE' === params.state &&
                <Button type="primary" style={{marginLeft: '20px'}} onClick={this.changeState}>划转</Button>}
                {['INIT', 'INVALID'].indexOf(params.state) >= 0 &&
                <Popconfirm ref="pop" title="确认要删除该客户?" defaultVisible={false} onConfirm={() => {
                  if (_this.selectedRowKeys.length <= 0) {
                    return;
                  }
                  _this.remove(_this.selectedRowKeys);
                }}>
                  <Button type="danger">批量删除</Button>
                </Popconfirm>}
              </div>
              <SearchInput search={this.handleSearch}/>
            </div>
          </div>
          <div style={{marginTop: 20}}>
            <Table rowKey="id"
                   {...tableRow}
                   loading={this.props.customer.loading}
                   columns={this.columns}
                   pagination={{...this.state.pagination, total: this.props.customer.total}}
                   dataSource={this.props.customer.list}
                   onChange={this.getList}

            />
          </div>
        </div>
      </Card>
      {['INIT', 'FOLLOW'].indexOf(params.state) >= 0 && <AddCustomer key={this.state.addKey}
                                                                     type={this.props.type}
                                                                     addVisible={this.state.addVisible}
                                                                     onSubmit={this.addCustomer}
                                                                     onCancel={() => {
                                                                       this.setState({
                                                                         addVisible: false
                                                                       })
                                                                     }}/>}
      {'INIT' === params.state && <Allocate key={this.state.acclocateKey}
                                            num={this.selectedRowKeys.length}
                                            visible={this.state.allocateVisible}
                                            userList={this.props.user.groupList}
                                            onSubmit={this.allocate}
                                            onCancel={() => {
                                              this.setState({
                                                allocateVisible: false
                                              })
                                            }
                                            }
      />}
      {'FOLLOW' === params.state && <Apply key={this.state.applyKey}
                                           visible={this.state.applyVisible}
                                           onSubmit={this.apply}
                                           onCancel={() => {
                                             this.setState({
                                               applyVisible: false
                                             })
                                           }}/> }
      {
        ('LOSE' === params.state||'FOLLOW' === params.state) && <Modal title="划转回归池"
                                          onOk={this.changeStateSub}
                                          onCancel={() => {
                                            this.setState({
                                              changeVisible: false
                                            })
                                          }}
                                          visible={this.state.changeVisible}
        >
          <div className="flex-row flex-aCenter">
            <div style={{width: '60px'}}>回归池:</div>
            <Select value={this.state.changeStateValue || 0} onChange={(val) => {
              this.setState({
                changeStateValue: val
              })
            }
            } style={{width: '120px'}}>
              <Option value={0}>初始池</Option>
              <Option value='PUBLIC'>公共资源池</Option>
              <Option value='PRIVATE'>私有资源池</Option>
            </Select>
          </div>
        </Modal>
      }
      {/* <Modal title={editObj.id ? "编辑产品":"新增产品"}
       onOk={this.submit}
       onCancel={this.handleCancel}
       visible={this.state.isvisible}>
       <Form ref="productForm" className={styles.modal}>
       <div className="flex-row">
       <div className="flex1">
       <FormItem label="产品名称">
       {getFieldDecorator('name', {
       initialValue:editObj.name || '',
       rules: [{
       required: true, message: '请输入产品名称'
       }],
       })(
       <Input placeholder='请输入产品名称' style={{width:"80%"}}  />
       )}
       </FormItem>
       </div>
       <div className="flex1">
       <FormItem label="合同模板">
       {getFieldDecorator('template',{
       initialValue:editObj.template || '',
       })(
       <Input placeholder='请输入合同模板' style={{width:"80%"}}/>
       )}
       </FormItem>
       </div>
       </div>
       <div className="flex-row">
       <div className="flex1">
       <FormItem label="产品类型">
       {getFieldDecorator('type',{
       initialValue: editObj.type || productType[0].key,
       rules:[{
       required:true,
       message:'请选择产品类型'
       }]
       })(
       <Select style={{width:"80%"}}>
       {productType.map(item=><Option key={item.key} value={item.key}>{item.name}</Option>)}
       </Select>
       )}
       </FormItem>
       </div>
       <div className="flex1">
       <FormItem label="产品状态">
       {getFieldDecorator('state',{
       initialValue: editObj.state || productStatus[0].key,
       rules:[{
       required:true,
       message:'请选择产品状态'
       }]
       })(
       <Select style={{width:"80%"}}>
       {productStatus.map(item=><Option key={item.key} value={item.key}>{item.name}</Option>)}
       </Select>
       )}
       </FormItem>
       </div>
       </div>
       <FormItem label="产品内容">
       {getFieldDecorator('content',{
       initialValue:editObj.content || '',
       })(
       <Input.TextArea placeholder='请输入产品内容'  style={{height:"70px"}}  />
       )}
       </FormItem>
       <FormItem label="备注">
       {getFieldDecorator('remark',{
       initialValue:editObj.remark || '',
       })(
       <Input.TextArea placeholder='请输入产品备注' style={{height:"70px"}}  />
       )}
       </FormItem>
       </Form>
       </Modal>*/}
    </PageHeaderLayout>)
  }
}
